<?php

namespace website\controllers;

use common\models\UserCoupon;
use Yii;
use common\helpers\Util;
use common\helpers\Pager;
use common\helpers\Checker;
use common\helpers\Uploader;
use common\server\sms\SmsCaptcha;
use common\models\User;
use common\models\Recharge;
use common\models\Message;
use common\models\UserLogin;
use common\models\UserCollection;
use common\models\UserAccountChange;
use website\helpers\Render;

class UserController extends Controller {

    // 登陆白名单
    public $whiteList = [
        'register', 'login'
    ];
    
    /**
     * @inheritdoc
     * check login
     */
    public function behaviors()
    {
        return [
            // @name 会员登陆校验hook
            // @return Yii::$app->user = login user, you can use as $this->user/$this->getUser()
            'access' => [
                'class' => \website\behaviors\PermissionHook::className(),
            ],
        ];
    }
    
    /**
     * 雇主注册页面
     * @return mixed
     */
    public function actionRegister()
    {
        $rule = [
            'param' => [
                'mobile' => ['手机号', ['mobile', 'required']],
                'password' => ['密码', ['password', 'required']],
                'role' => ['角色', ['inkey' => User::$roleSelector, 'required'], ['inkey' => '您的输入有误，或刷新页面重试', 'required' => '您的输入有误，或刷新页面重试']],
                'captcha' => ['验证码', ['number', 'length' => 6, 'required']],
//                'inviter' => ['邀请码', 'string', 'max' => 32],
                'inviter' => ['邀请码', ['int']],
            ]
        ];
        // 参数异常，渲染错误页面
        if( ! $this->request->isPost) {
            return $this->render('register', [
                'relate' => json_encode($rule),
            ]);
        }
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->error($checker['message'].'（Invalid Param）', 'user/register');
        }
        if( ! SmsCaptcha::validate($params['captcha'], 'register')) {
            return $this->error('验证码错误（Invalid Captcha）', 'user/register');
        }
        if(User::find()->where(['or', ['username' => $params['mobile']], ['mobile' => $params['mobile']]])->exists()) {
            return $this->error('该手机号已被注册', 'user/register');
        }
        $params['username'] = $params['mobile'];
        $params['nickname'] = Render::substring($params['mobile'], 'mobile');
        $user = new User();
        $user->loads($params, ['password' => 'password_digest']);
        $user->registor = User::RegistorOuter;
        if ( ! $user->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($this->buildModelError($user), 'user/register');
        }
        if ($user->tregister()) {
            // 发放雇主注册送优惠劵
            if($user->employer()) {
                UserCoupon::creator(UserCoupon::RegisterDeliver, $user->id);
            }
            // 发放邀请送优惠劵
            if($user->employer()) {
                UserCoupon::creator(UserCoupon::RegisterDeliver, $user->id);
                // 发放邀请送优惠劵
                if($user->invitor) {
                    UserCoupon::creator(UserCoupon::RegisterInviter, $user->inviter);
                }
            }
            // 保存成功
            return $this->success('恭喜您，注册成功', [
                ['title' => '前往完善个人资料', 'url' => ($user->controller()).'/information'],
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('注册失败，请重试', 'user/register');
    }
    
    /**
     * 登陆页面
     * @return string
     */
    public function actionLogin()
    {
        if($this->isLogin()) {
            return $this->skip('您已经登陆过了', [
                ['title' => '前往个人中心', 'url' => ($this->user->controller()).'/index'],
            ]);
        }
        $rule = [
            'param' => [
                'username' => ['登录名', ['username', 'required']],
                'password' => ['密码', ['password', 'required']],
                'role' => ['角色', ['inkey' => User::$roleSelector, 'required'], ['inkey' => '您的输入有误，或刷新页面重试', 'required' => '您的输入有误，或刷新页面重试']],
            ],
        ];
        if( ! $this->request->isPost) {
            return $this->render('login', [
                'relate' => json_encode($rule),
            ]);
        }
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        // 参数异常，渲染错误页面
        if($checker['code'] != Checker::SuccessCode) {
            return $this->error($checker['message'], 'user/login');
        }
        /** @var User $user */
        $user = User::find()->where(['username' => $params['username'], 'role' => $params['role']])->one();
        if(empty($user)) {
            return $this->error('无效的用户（Invalid User）', 'user/login');
        }
        if( ! $user->validatePassword($params['password'])) {
            return $this->error('账号密码不匹配', 'user/login');
        }
        if( ! $user->valid()) {
            return $this->error('无效的用户（Invalid User）', 'user/login');
        }
        $user->login();
        return $this->success('登陆成功，欢迎', $user->controller().'/index');
    }
    
    public function actionLogout()
    {
        $this->user->logout();
        return $this->success('您已成功退出', 'welcome/index');
    }
    
    /**
     * 头像设置
     * @return mixed
     */
    public function actionPhoto()
    {
        if( ! $this->request->isPost) {
            return $this->render('photo', [
                'user' => $this->user,
            ]);
        }
        // 开始上传图片
        $configurate = require Yii::getAlias('@common/config/uploader.php');
        // 上传头像
        $loader = (new Uploader($configurate['designer']))->upload('photo');
        if($loader['code'] == SuccessCode) {
            Util::trashUpload($this->user->photo);
            $this->user->photo = $loader['path'];
            if($this->user->save()) {
                return $this->success('头像上传成功', 'user/photo');
            }
            else {
                return $this->error('系统异常，请重新上传', 'user/photo');
            }
        }
        else {
            return $this->error('头像上传失败：'.$loader['message'], 'user/photo');
        }
    }
    
    /**
     * 资金明细列表
     * @return mixed
     */
    public function actionBalanceChange()
    {
        if( ! $this->request->isPost) {
            if($this->user->designer() && ! $this->user->information()) {
                return $this->error('请先完善个人资料', 'designer/information');
            }
            return $this->render('balance-change');
        }
        $params = $this->request->post();
        $rules = [
            'param' => [
                'type' => ['类型', ['inkey' => UserAccountChange::$changeSelector]],
                'start' => ['开始时间', ['date' => 'Y-m-d']],
                'end' => ['结束时间', ['date' => 'Y-m-d']],
            ],
        ];
        $checker = Checker::authentication($rules, $params);
        if($checker['code'] != SuccessCode) {
            return $this->json('Param.Error', $checker['message']);
        }
        foreach(['start', 'end'] as $key) {
            $params[$key] = strtotime($params[$key]);
        }
        $params['user_id'] = $this->user->id;
        $query = UserAccountChange::filterConditions(UserAccountChange::initCondition(['user_id', 'type', ['created_at', '>=', 'start'], ['created_at', '<=', 'end']], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }
    
    /**
     * 修改密码
     * @return mixed
     */
    public function actionChangePassword()
    {
        $rule = [
            'param' => [
                'oldpassword' => ['原密码', ['password', 'required']],
                'password' => ['新密码', ['password', 'required']],
                'repassword' => ['重复密码', ['password', 'required']],
                'captcha' => ['验证码', ['number', 'length' => 6, 'required']],
            ]
        ];
        // 参数异常，渲染错误页面
        if( ! $this->request->isPost) {
            return $this->render('change-password', [
                'relate' => json_encode($rule),
            ]);
        }
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->error($checker['message'].'（Invalid Param）', 'user/change-password');
        }
        if( ! SmsCaptcha::validate($params['captcha'], 'change-password')) {
            return $this->error('验证码错误（Invalid Captcha）', 'user/change-password');
        }
        $user = User::findOne($this->user['id']);
        if( ! $user->validatePassword($params['oldpassword'])) {
            return $this->error('旧密码错误（Invalid Old Password）', 'user/change-password');
        }
        $user->password_digest = $params['password'];
        if( ! $user->save()) {
            return $this->error('密码修改失败（System Error）', 'user/change-password');
        }
        $user->login();
        return $this->success('密码修改成功（Changed Password）', 'user/change-password');
    }
    
    /**
     * 修改绑定手机号
     * @return mixed
     */
    public function actionChangeMobile()
    {
        $rule = [
            'param' => [
                'mobile' => ['手机号', ['mobile', 'required']],
                'captcha' => ['验证码', ['number', 'length' => 6, 'required']],
            ]
        ];
        // 参数异常，渲染错误页面
        if( ! $this->request->isPost) {
            return $this->render('change-mobile', [
                'relate' => json_encode($rule),
            ]);
        }
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->error($checker['message'].'（Invalid Param）', 'user/change-mobile');
        }
        if( ! SmsCaptcha::validate($params['captcha'], 'change-mobile')) {
            return $this->error('验证码错误（Invalid Captcha）', 'user/change-mobile');
        }
        $user = User::findOne($this->user['id']);
        $user->mobile = $params['mobile'];
        if( ! $user->save()) {
            return $this->error('绑定手机修改失败（System Error）', 'user/change-mobile');
        }
        $user->login();
        return $this->success('绑定手机修改成功（Changed Mobile）', 'user/change-mobile');
    }
    
    /**
     * 发送手机验证码
     * @return mixed
     */
    public function actionCaptchaMobile()
    {
        $rule = [
            'param' => [
                'type' => ['短信类型', ['in' => SmsCaptcha::$templateSelector, 'required']],
            ]
        ];
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', '请刷新页面重试！');
        }
        // 加锁
        $lockKey = $params['type'].'.'.$this->user['mobile'];
        if( ! Util::lock($lockKey)) {
            return $this->json('Send.Failed', '请不要频繁的操作，稍后再试！');
        }
        if(SmsCaptcha::captcha($this->user['mobile'], $params['type'])) {
            return $this->json(SuccessCode, '短信验证码已发送，请注意查收！');
        }
        // 解锁
        // Util::unLock($lockKey);
        return $this->json('Send.Failed', '短信验证码发送失败，请重试！');
    }
    
    /**
     * 充值申请
     * @return string json
     */
    public function actionRecharge()
    {
        $rule = [
            'param' => [
                'amount' => ['金额', ['int', 'gt' => 0, 'required']],
                'remark' => ['备注', ['int', 'length' => 6, 'required']],
            ],
        ];
        if( ! $this->request->isPost) {
            return $this->render('recharge', [
                'remark' => rand(100000, 999999),
                'relate' => json_encode($rule)
            ]);
        }
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        if(Recharge::initialize($params)) {
            return $this->json(SuccessCode, '充值申请成功，请尽快完成支付宝转账');
        }
        return $this->json('System.Error', '充值申请异常，请稍后重试');
    }
    
    /**
     * 站内信列表
     * @return mixed
     */
    public function actionMessageList()
    {
        if( ! $this->request->isPost) {
            if($this->user->designer() && ! $this->user->information()) {
                return $this->error('请先完善个人资料', 'designer/information');
            }
            return $this->render('message-list', [
                'status' => $this->request->get('status'),
            ]);
        }
        $params['status'] = $this->request->get('status');
        $params['receiver_id'] = $this->user->id;
        $query = Message::filterConditions(Message::initCondition(['receiver_id', 'status'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }
    
    /**
     * 阅读站内信
     * @return mixed
     */
    public function actionMessage()
    {
        /** @var $message Message */
        if( ! $message = Message::canEdit($this->request->get('id'), ['receiver_id' => $this->user->id])) {
            return $this->error('请求异常，请稍后刷新页面重试', 'welcome/index');
        }
        if($message->status == Message::StatusUnread) {
            $message->reador();
        }
        // 参数异常，渲染错误页面
        return $this->render('message', [
            'message' => $message,
        ]);
    }
    
    /**
     * 收藏管理
     * @return string json
     */
    public function actionCollection()
    {
        $rule = [
            'param' => [
                'id' => ['编号', ['int', 'required']],
                'handle' => ['操作', ['in' => ['collection', 'revoke'], 'required']],
                'type' => ['类型', ['inkey' => UserCollection::$typeSelector, 'required']],
            ]
        ];
        $params = $this->request->post();
        $checker = Checker::authentication($rule, $params);
        if($checker['code'] != Checker::SuccessCode) {
            return $this->json('Invalid.Param', $checker['message']);
        }
        if($params['handle'] == 'collection') {
            if(UserCollection::find()->where(['collection_id' => $params['id'], 'user_id' => $this->user->id, 'type' => $params['type']])->exists()) {
                return $this->json(SuccessCode, '收藏成功');
            }
            $attribute = [
                'collection_id' => $params['id'],
                'type' => $params['type'],
            ];
            if(UserCollection::creator($attribute)) {
                return $this->json(SuccessCode, '收藏成功');
            }
            return $this->json('System.Error', '收藏失败');
        }
        else {
            if( ! ($collection = UserCollection::find()->where(['collection_id' => $params['id'], 'user_id' => $this->user->id, 'type' => $params['type']])->one())) {
                return $this->json('Request.Error', '请求异常，请稍后刷新页面重试');
            }
            if($collection->delete()) {
                return $this->json(SuccessCode, '已取消收藏');
            }
            return $this->json('System.Error', '取消失败');
        }
    }
}
